import { hashHistory } from 'dva/router';
import delay from '@/util/delay.js'

/**
 * 从服务器加载数据
 * @param kw 查询关键词
 * @param selectValue 查询范围
 * @param pagination 分页参数
 * @return {IterableIterator<Promise<any>>}
 */
async function searchDataFormServer({ kw, selectValue, pagination }) {
  console.log(`从服务器加载数据,查询条件:${kw}, 数据范围:${selectValue}, 分页条件:`, pagination)
  return new Promise((resolve, reject) => {
    const mock = {
      total: 30,
      current: pagination.current,
      list: [
        {
          id: 1,
          name: '张三',
          age: 23,
          address: '成都',
        },
        {
          id: 2,
          name: '李四',
          age: 24,
          address: '杭州',
        },
        {
          id: 3,
          name: '王五',
          age: 25,
          address: '上海',
        },
      ],
    }
    resolve(mock)
  })
}

export default {
  namespace: 'users',

  state: {
    // 搜索条件
    inputValue: '',
    selectValue: 0,

    // 数据表格
    list: [],
    pageSize: 3,
    total: 0,
    loading: false, // 控制加载状态
    current: 1, // 当前分页信息

    // 新增/编辑项
    currentItem: {}, // 当前操作的用户对象
    modalVisible: false, // 弹出窗的显示状态
    modalType: 'create', // 弹出窗的类型（添加用户，编辑用户）
  },

  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由变化
      history.listen(location => {
        if (location.pathname === '/index') {
          // 发起reducer调用
          dispatch({
            type: 'query'
          });
        }
      });
    },
  },

  effects: {
    /**
     *
     * @param payload 入参
     * @param select 用于获取指定dva model的state
     * @param call 用于发起对自定义函数的调用
     * @param put 用于发起对dva reducer 方法的调用
     * @return {IterableIterator<*>}
     */* query({ pagination = { current: 1, pageSize: 3 }, selectValue }, { select, call, put }) {
      yield put({
        type: 'showLoading'
      })
      const inputValue = yield select(state => state.users.inputValue)
      const realSelectValue = selectValue ? selectValue : yield select(state => state.users.selectValue)
      const resp = yield call(searchDataFormServer, { kw: inputValue, selectValue: realSelectValue, pagination })
      yield call(delay)
      console.log('响应结果', resp)
      yield put({
        type: 'querySuccess',
        pageData: resp,
        selectValue: realSelectValue
      })
    },
    /**
     * 提交表单
     * @param formData 表单数据
     * @param resolve 表单提交成功之后,执行该回调方法
     * @param select
     * @param call
     * @param put
     * @return {IterableIterator<*>}
     */* create({ formData, resolve }, { select, call, put }) {
      console.log('向服务器提交表单数据...', formData)
      yield put({
        type: 'showLoading'
      })
      yield call(delay)
      resolve()
      yield put({
        type: 'createSuccess',
        bizResult: {}
      })
      yield put({
        type: 'query'
      })
    },
    * 'delete'() {
    },
    * update() {
    },
  },
  reducers: {
    changeInput(state, { inputValue }) {
      return { ...state, inputValue }
    },
    changeSelect(state, { selectValue }) {
      return { ...state, selectValue }
    },
    /*
    * 控制加载状态的 reducer
    */
    showLoading(state, action) {
      return { ...state, loading: true };
    },

    /**
     * 控制 Modal 显示状态的 reducer
     */
    showModal(state) {
      return { ...state, modalVisible: true }
    },
    hideModal(state) {
      return { ...state, modalVisible: false }
    },
    /**
     * 使用静态数据返回
     */
    querySuccess(state, { pageData, selectValue }) {
      console.log('查询成功...')
      return { ...state, ...pageData, selectValue, loading: false };
    },
    createSuccess(state, { bizResult }) {
      console.log('表单数据新增成功!')
      return { ...state, loading: false, modalVisible: false }
    },
    deleteSuccess() {
    },
    updateSuccess() {
    },
  }
}
